#!/usr/bin/perl

# Written by Elihu Ihms (ihms@steelsnowflake.com)

#
# generates a UCSF chimera attribute list
# takes as input a tab or other whitespace-delimited datafile with two columns representing residue and (an) attribute
# see http://www.cgl.ucsf.edu/chimera/docs/ContributedSoftware/defineattrib/defineattrib.html
#

# Changelog:
# 09.09.2010	written

# default values
$argcounter			= 0;
$attribute_name		= 'false';
$match_mode			= 'any';
$recipient			= 'residues';
$atomspec_prefix	= '';
$atomspec_postfix	= '';

#go through the arguments and get their values
while ( $argcounter <= $#ARGV )
{
	if ( $ARGV[ $argcounter ] eq "-a" )
	{
		$attribute_name = $ARGV[ $argcounter +1 ];
		$argcounter++;
	}
	elsif ( $ARGV[ $argcounter ] eq "-m" )
	{
		$match_mode = $ARGV[ $argcounter +1 ];
		$argcounter++;
	}
	elsif ( $ARGV[ $argcounter ] eq "-r" )
	{
		$recipient = $ARGV[ $argcounter +1 ];
		$argcounter++;
	}
	elsif ( $ARGV[ $argcounter ] eq "-x" )
	{
		$atomspec_prefix = $ARGV[ $argcounter +1 ];
		$argcounter++;
	}
	elsif ( $ARGV[ $argcounter ] eq "-y" )
	{
		$atomspec_postfix = $ARGV[ $argcounter +1 ];
		$argcounter++;
	}
	elsif ($ARGV[ $argcounter ] eq "-h"){
		show_help();
	}
	
	$argcounter++;
}

if (-t STDIN){
	print STDERR "No pipe. Provide some data.\n";
	exit;
}

# argument sanity checks
@match_modes = ('any','non-zero','1-to-1');
if (not(grep $_ eq $match_mode, @match_modes)){
	die "Invalid match mode '$match_mode' specified.\nValid modes are 'any', 'non-zero', or '1-to-1'.\n";
}
@recipients = ('atoms','residues','molecules');
if (not(grep $_ eq $recipient, @recipients)){
	die "Invalid recipient type '$recipient' specified.\nValid recipients are 'atoms','residues', or 'molecules'.\n";
}

# get passed dataset
@data = <STDIN>;
chomp(@data);

# start outputting attribute file
print "#\n# generated by makeattr\n";
print "# a-spec prefix: '$atomspec_prefix'\n";
print "# a-spec postfix: '$atomspec_postfix'\n";
print "attribute: $attribute_name\n";
print "match mode: $match_mode\n";
print "recipient: $recipient\n";
print "#\n";

$sum = 0;
foreach(@data)
{
	if($_ =~ /^\s*(\S+)\s+(\S+)\s*/){
		print "\t".$atomspec_prefix.":".$1.$atomspec_postfix."\t".$2."\n";
	}
}

sub show_help
{
	print "makeattr -a <attribute name> -m (any|non-zero|1-to-1) -r (atoms|residues|molecules) -x <prefix> -y <postfix>\n";
	exit;
}